package IO;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-11-29
 * Time: 9:13
 */
public class Demo13 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入指定目录:");
        String path = scanner.next();
        File root = new File(path);
        if(!root.isDirectory()) {
            System.out.println("非法目录!");
            return;
        }

        System.out.println("请输入要删除的单词:");
        String word = scanner.next();
        scanDir(root, word);
    }

    private static void scanDir(File root, String word) throws IOException {
        File[] files = root.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File f :
                files) {
            if (f.isDirectory()) {
                scanDir(f, word);
            } else {
                dealFile(f, word);
            }
        }
    }

    private static void dealFile(File f, String word) throws IOException {
        if(f.getName().contains(word)) {
            System.out.println(f.getCanonicalPath());
            return;
        }
        try(InputStream inputStream = new FileInputStream(f)) {
            Scanner scanner = new Scanner(inputStream, "utf8");
            while (scanner.hasNextLine()) {
                String string = scanner.nextLine();
                if (string.contains(word)) {
                    System.out.println(f.getCanonicalPath());
                    break;
                }
            }
        }
    }
}
